<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import LoginApi from '../api/loginApi.js'
import userApi from '../api/userApi.js'
import { User, Lock, Key, UserFilled } from "@element-plus/icons-vue";

const user = ref({
  username: '',
  password: '',
  captcha: '',
  key: ''
});

// 添加登录类型选择
const loginType = ref('user'); // 默认为用户登录

// 注册表单数据
const registerForm = ref({
  username: '',
  password: '',
  phone: '',
});

// 控制显示状态
const isRegisterMode = ref(false);
const registerLoading = ref(false);

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度在 6 到 30 个字符', trigger: 'blur' }
  ],

  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],

};

const registerFormRef = ref(null);

onMounted(function(){
  localStorage.removeItem("token");
  loadCaptcha();
})

const router = useRouter();
const captcha = ref("");

// 检查错误是否为验证码错误
const isCaptchaError = (error) => {
  const errorMessage = error.message || error.toString();
  return errorMessage.includes('验证码') ||
         errorMessage.includes('captcha') ||
         errorMessage.includes('验证码错误') ||
         errorMessage.includes('验证码不正确') ||
         errorMessage.includes('验证码已过期') ||
         errorMessage.includes('Captcha') ||
         errorMessage.toLowerCase().includes('captcha error');
}

// 切换到注册模式
const switchToRegister = () => {
  isRegisterMode.value = true;
  // 重置注册表单
  registerForm.value = {
    username: '',
    password: '',
    phone: '',
  };
};

// 切换到登录模式
const switchToLogin = () => {
  isRegisterMode.value = false;
  // 重置登录表单
  user.value = {
    username: '',
    password: '',
    captcha: '',
    key: user.value.key
  };
};

// 注册功能
const onRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    await registerFormRef.value.validate();
  } catch (error) {
    return;
  }

  try {
    await ElMessageBox.confirm('确定要注册该账号吗？');
  } catch {
    return;
  }

  registerLoading.value = true;
  let registrationSuccess = false;
  
  try {
    const submitData = { ...registerForm.value };
    
    await userApi.add(submitData);
    
    registrationSuccess = true;
    
    ElMessage({
      type: 'success',
      message: '注册成功！请使用新账号登录'
    });
    
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '注册失败: ' + (error.message || '请重试')
    });
  } finally {
    registerLoading.value = false;
  }
  
  if (registrationSuccess) {
    switchToLogin();
  }
};


const onSubmit = async () => {
  try {
    const username = user.value.username;

    // 检查账号是否为空
    if (!username || username.trim() === '') {
      ElMessage.error('请输入账号');
      return;
    }

    let loginSuccess = false;

    if (loginType.value === 'user') {
      // 用户登录
      try {
        const userRes = await LoginApi.userLogin(user.value);
        if (userRes && userRes.trim() !== '') {
          localStorage.setItem("token", userRes);
          const userInfo = await LoginApi.loginUserInfo();

          if (userInfo && userInfo.id) {
            await handleLoginSuccess(userInfo, 'user');
            loginSuccess = true;
          }
        }
      } catch (userError) {
        if (isCaptchaError(userError)) {
          ElMessage.error('验证码错误，请重新输入');
          loadCaptcha();
        } else {
          ElMessage.error('用户登录失败，请检查账号密码');
        }
        return;
      }
    } else if (loginType.value === 'admin') {
      // 管理员登录
      try {
        const adminRes = await LoginApi.adminLogin(user.value);
        if (adminRes && adminRes.trim() !== '') {
          localStorage.setItem("token", adminRes);
          const adminInfo = await LoginApi.loginAdminInfo();

          if (adminInfo && adminInfo.id) {
            await handleLoginSuccess(adminInfo, 'admin');
            loginSuccess = true;
          }
        }
      } catch (adminError) {
        if (isCaptchaError(adminError)) {
          ElMessage.error('验证码错误，请重新输入');
          loadCaptcha();
        } else {
          ElMessage.error('管理员登录失败，请检查账号密码');
        }
        return;
      }
    }

    if (!loginSuccess) {
      ElMessage.error('登录失败，请检查账号密码');
    }

  } catch (error) {
    console.error('登录过程中发生错误:', error);
    if (isCaptchaError(error)) {
      ElMessage.error('验证码错误，请重新输入');
      loadCaptcha();
    } else {
      ElMessage.error('登录失败，请重试');
    }
  }
}

// 处理登录成功
const handleLoginSuccess = async (userInfo, type) => {
  try {
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
    localStorage.setItem('userType', type);
    localStorage.setItem('username', userInfo.username || userInfo.name || '用户');
    
    ElMessage({
      type: 'success',
      message: `${type === 'admin' ? '管理员' : '用户'}登录成功！`
    });
    
    // 根据用户类型跳转到不同页面
    if (type === 'admin') {
      router.push('/index'); // 管理员跳转到管理后台
    } else {
      router.push('/goods'); // 普通用户跳转到商品浏览页面
    }
  } catch (error) {
    console.error('处理登录成功时发生错误:', error);
    ElMessage.error('登录处理失败，请重试');
  }
};

// 加载验证码
const loadCaptcha = async () => {
  try {
    const res = await LoginApi.captcha();
    if (res && res.key && res.base) {
      user.value.key = res.key;
      captcha.value = res.base;
    } else {
      console.error('验证码API响应格式错误:', res);
      ElMessage.error('验证码加载失败');
    }
  } catch (error) {
    console.error('加载验证码失败:', error);
    ElMessage.error('验证码加载失败，请刷新页面重试');
  }
}

</script>


<template>
  <div class="login-bg">
    <!-- 登录表单 -->
    <el-form v-if="!isRegisterMode" class="form-login" :model="user">
      <el-row>
        <el-col :span="10">
          <img style="width: 100px" src="@/assets/111.jpg" alt="中享思途" />
        </el-col>
        <el-col :span="14">
          <h1>系统登录</h1>
        </el-col>
      </el-row>

      <!-- 添加登录类型选择 -->
      <el-form-item>
        <el-radio-group v-model="loginType" style="width: 100%; display: flex; justify-content: center;">
          <el-radio label="user" size="large">用户登录</el-radio>
          <el-radio label="admin" size="large">管理员登录</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-input v-model="user.username"
                  placeholder="请输入账号"
                  :prefix-icon="User"
                  maxlength="16"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="user.password"
                  placeholder="请输入密码"
                  show-password
                  :prefix-icon="Lock"
                  maxlength="16"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="user.captcha"
                  placeholder="验证码"
                  :prefix-icon="Key"
                  maxlength="5"
                  style="width: 220px; margin-right: 15px;"
                  class="input-verCode"></el-input>
        <img :src="captcha"
             class="img-verCode" @click="loadCaptcha">
      </el-form-item>
      <el-form-item>
        <el-button class="btn-login" type="success" @click="onSubmit">
          登录
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button class="btn-register" type="primary" @click="switchToRegister">
          注册新账号
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 注册表单 -->
    <el-form v-else
             ref="registerFormRef"
             class="form-register"
             :model="registerForm"
             :rules="registerRules"
             label-width="80px">
      <el-row>
        <el-col :span="10">
          <img style="width: 80px" src="@/assets/111.jpg" alt="中享思途" />
        </el-col>
        <el-col :span="14">
          <h1>用户注册</h1>
        </el-col>
      </el-row>

      <!-- 必填字段 -->
      <el-form-item label="账号" prop="username">
        <el-input v-model="registerForm.username"
                  placeholder="请输入账号"/>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="registerForm.password"
                  type="password"
                  placeholder="请输入密码"/>
      </el-form-item>


      <el-form-item label="电话" prop="phone">
        <el-input v-model="registerForm.phone"
                  placeholder="请输入联系电话"/>
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="registerForm.gender"
                   placeholder="请选择性别"
                   style="width: 100%"
                   clearable>
          <el-option label="男" :value="1"/>
          <el-option label="女" :value="2"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button class="btn-register"
                   type="success"
                   @click="onRegister"
                   :loading="registerLoading">
          注册
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button class="btn-back"
                   type="info"
                   @click="switchToLogin">
          返回登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>

.login-bg{
  height: 100vh;
  background-image: url('../assets/111.jpg');
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: fixed;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-login, .form-register{
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

.form-register {
  width: 450px;
  max-height: 80vh;
  overflow-y: auto;
}

.btn-login, .btn-register, .btn-back{
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 6px;
  transition: all 0.3s;
  margin-bottom: 10px;
}

.btn-login:hover, .btn-register:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.3);
}

.btn-back:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(144, 147, 153, 0.3);
}

h1{
  text-align: center;
  font-size: 24px;
  margin-bottom: 30px;
  height: 50px;
  line-height: 50px;
  color: #333;
  font-weight: 600;
}

.input-verCode{
  width: 220px;
  margin-right: 15px;
}

.img-verCode{
  width: 120px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.3s;
}

.img-verCode:hover {
  border-color: #409eff;
}

/* 注册表单特殊样式 */
.form-register .el-form-item {
  margin-bottom: 20px;
}

.form-register .el-form-item__label {
  font-weight: 600;
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-login, .form-register {
    width: 90%;
    padding: 30px 20px;
  }
  
  .form-register {
    width: 95%;
  }
  
  .input-verCode {
    width: 180px;
  }
  
  .img-verCode {
    width: 100px;
    height: 35px;
  }
}

/* 滚动条样式 */
.form-register::-webkit-scrollbar {
  width: 6px;
}

.form-register::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-register::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.form-register::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

</style>
